package com.syys.example;

import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.junit.jupiter.api.Test;

/**
 * 发布消息
 */
public class Producer {

    private DefaultMQProducer defaultMQProducer;

    public void init() {
        defaultMQProducer = new DefaultMQProducer("TEST01_PRODUCER");
        defaultMQProducer.setNamesrvAddr("127.0.0.1:9876");
        try {
            defaultMQProducer.start();
        } catch (MQClientException e) {
            System.out.println("启动失败！");
        }
    }

    @Test
    public void producer() throws InterruptedException, RemotingException, MQClientException, MQBrokerException {
        init();
        for (int i = 0; i < 100; i++) {
            Message message = new Message("TopicQuickStart", "TagA", ("Hello RocketMQ " + i).getBytes());
            SendResult result = defaultMQProducer.send(message);
            System.out.println(result);
        }
        destroy();
    }

    public void destroy() {
        defaultMQProducer.shutdown();
    }

}
